import { HttpService } from '@nestjs/axios';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AxiosRequestConfig } from 'axios';
import { lastValueFrom } from 'rxjs';
import { defaultAxiosConfig } from 'src/common/utils';
import { ApiCommonRes } from 'src/common/model/res-common';

@Injectable()
export class OnlyHttpService {
  apiServer: string;
  constructor(private readonly httpService: HttpService, private readonly config: ConfigService) {
    this.apiServer = this.config.get('API_HOST') as string;
  }
  post = async <T = any>(url: string, data?: any, config?: AxiosRequestConfig) => {
    const res = await this.httpService.post<ApiCommonRes<T>>(url, data, {
      ...config,
      ...defaultAxiosConfig,
      baseURL: this.apiServer,
    });
    const resData = await lastValueFrom(res);
    Logger.log([resData.config.url, resData.config.headers, resData.config.data], '请求内容-OnlyHttp');
    Logger.log([resData.status, resData.data], '返回内容-OnlyHttp');

    return resData.data;
  };

  get = async <T = any>(url: string, config?: AxiosRequestConfig) => {
    const res = await this.httpService.get<ApiCommonRes<T>>(url, {
      ...defaultAxiosConfig,
      ...config,
      baseURL: this.apiServer,
    });
    const resData = await lastValueFrom(res);
    Logger.log([resData.config.url, resData.config.headers, resData.config.params], '请求内容-OnlyHttp');
    Logger.log([resData.status, resData.data], '返回内容-OnlyHttp');

    return resData.data;
  };
}
